# -*- coding: UTF-8 -*-
# 单层感知机，构建训练集中各个设备的HI曲线

import numpy as np
from sklearn.preprocessing import StandardScaler
import keras
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Dense, Dropout
import matplotlib.pyplot as plt

# 数据集路径
filepath_data = '/home/zxl/zy/Predict_Module/Data/RUL_Turbofan/train_FD001.txt'
data_all = np.loadtxt(filepath_data)  # (20631, 26) 数组


# 绘制六个特征图（5#）
# scalar = StandardScaler()
# data_all = scalar.fit_transform(data_all)
# print data_all[847:1116, [6, 7, 8, 11, 12, 13]]
# plt.plot(data_all[847:1116, 13])
# plt.savefig('/home/zxl/zy/Predict_Module/Data/RUL_Turbofan/FD001_HI/train/001.png')


def Z_Score(data):
    lenth = len(data)
    total = sum(data)
    ave = float(total) / lenth
    tempsum = sum([pow(data[i] - ave, 2) for i in range(lenth)])
    tempsum = pow(float(tempsum) / lenth, 0.5)
    for i in range(lenth):
        data[i] = (data[i] - ave) / tempsum
    return data


# 对需要的特征z-score
# scalar = StandardScaler()
# data_feature = scalar.fit_transform(data_all[:, [6, 7, 8, 11, 12, 13]])
data_index = data_all[:, [0, 1]]
f1 = Z_Score(data_all[:, 6])
f1 = np.reshape(f1, (f1.shape[0], 1))
f2 = Z_Score(data_all[:, 7])
f2 = np.reshape(f2, (f2.shape[0], 1))
f3 = Z_Score(data_all[:, 8])
f3 = np.reshape(f3, (f3.shape[0], 1))
f4 = Z_Score(data_all[:, 11])
f4 = np.reshape(f4, (f4.shape[0], 1))
f5 = Z_Score(data_all[:, 12])
f5 = np.reshape(f5, (f5.shape[0], 1))
f6 = Z_Score(data_all[:, 13])
f6 = np.reshape(f6, (f6.shape[0], 1))
data_feature = np.hstack((data_index, f1, f2, f3, f4, f5, f6))

# 获取单层感知机的训练数据
data_start_end = []  # 所有发动机的首尾数据 (200, 8)
for n in range(1, int(data_all[-1, 0]) + 1):
    data_engine = []  # 每个发动机的数据
    for i in range(len(data_feature)):
        if (data_feature[i][0] == n):
            data_engine.append(data_feature[i, :])  # 机器序号、机器周期号+6个特征
    data_engine = np.array(data_engine)
    data_start_end.append(data_engine[0])
    data_start_end.append(data_engine[-1])
data_start_end = np.array(data_start_end)

# 为感知机输入数据赋予标签：开始时刻为1，结束时刻为0
engine_start = data_start_end[::2]
engine_start = np.append(engine_start, [[1]] * len(engine_start), axis=1)
engine_end = data_start_end[1::2]
engine_end = np.append(engine_end, [[0]] * len(engine_end), axis=1)
data = np.vstack((engine_start, engine_end))  # (200, 9)
np.random.shuffle(data)
data_x = data[:, 2:8]
data_y = data[:, -1]  # (200,)
# print data_x, data_y

# 单层感知机模型
# '''
learning_rate = 0.01
hidden_neuron = 30
batch_size = 30
epochs = 500
model = Sequential()
model.add(Dense(hidden_neuron, activation='relu', input_shape=(6,)))
model.add(Dropout(0.05))
model.add(Dense(1))
model.summary()
model.compile(loss='mse', optimizer=keras.optimizers.Adam(lr=learning_rate), metrics=['accuracy'])
# history = model.fit(data_x, data_y, batch_size=batch_size, epochs=epochs)
history = model.fit(data_x, data_y, batch_size=batch_size, epochs=epochs, validation_split=0.2)
model.save('/home/zxl/zy/Predict_Module/Data/RUL_Turbofan/FD001_HI/FD001.h5')
# '''

# 为各个引擎生成HI
# '''
# data_hi = data_all[:, [0, 1, 6, 7, 8, 11, 12, 13]]
# scalar = StandardScaler()
# data_hi_feature = scalar.fit_transform(data_all[:, [6, 7, 8, 11, 12, 13]])
# data_hi_index = data_all[:, [0, 1]]
# data_hi = np.hstack((data_hi_index, data_hi_feature))
for n in range(1, int(data_feature[-1, 0]) + 1):  # 100
    data_pre_input = []
    for i in range(len(data_feature)):
        if (data_feature[i][0] == n):
            data_pre_input.append(data_feature[i, 2:])
    # scalar = StandardScaler()
    # data_pre_input = scalar.fit_transform(data_pre_input)  # 数据标准化
    data_pre_input = np.array(data_pre_input)
    model = load_model('/home/zxl/zy/Predict_Module/Data/RUL_Turbofan/FD001_HI/FD001.h5')  # 加载模型
    pre = model.predict(data_pre_input)  # 模型预测结果：(T,1)二维数组
    # print pre
    np.savetxt('/home/zxl/zy/Predict_Module/Data/RUL_Turbofan/FD001_HI/train/FD00' + str(n) + '_HI.txt', pre, fmt='%f')
    # 绘制HI曲线图
    plt.plot(pre)
    plt.savefig('/home/zxl/zy/Predict_Module/Data/RUL_Turbofan/FD001_HI/train/FD001_' + str(n) + '.png')
    plt.clf()
    print("已完成第" + str(n) + "个HI")
# '''
